using AntdUI;
using AntdUI.Svg;
using Fiddler;
using Grpc.Core;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using TangCaptureTraffic.Forms;
using TangCaptureTraffic.Manager;
using TangCaptureTraffic.Models;
using TangCaptureTraffic.Services;

namespace TangCaptureTraffic
{
    /// <summary>
    /// 主窗体类，继承自AntdUI.Window，用于显示网络流量捕获界面
    /// </summary>
    public partial class MainForm : AntdUI.Window
    {
        private readonly IUIService _uiService;
        private readonly ISessionService _sessionService;
        private readonly IConfigurationService _configurationService;
        private readonly ISessionFormattingService _sessionFormattingService;
        /// <summary>
        /// 主窗体构造函数，初始化界面组件和Fiddler代理服务
        /// </summary>
        public MainForm() : this(false)
        {
        }

        /// <summary>
        /// 主窗体构造函数，可选择是否跳过初始化步骤
        /// </summary>
        /// <param name="skipInitialization">如果为true，则跳过初始化步骤（由启动窗体完成）</param>
        public MainForm(bool skipInitialization)
        {


            // 从服务容器获取服务实例
            _uiService = ServiceContainer.Instance.GetService<IUIService>();
            _sessionService = ServiceContainer.Instance.GetService<ISessionService>();
            _configurationService = ServiceContainer.Instance.GetService<IConfigurationService>();
            _sessionFormattingService = ServiceContainer.Instance.GetService<ISessionFormattingService>();

            // 初始化窗体组件
            InitializeComponent();

            // 设置键盘事件预览
            this.KeyPreview = true;
            this.KeyDown += MainForm_KeyDown;

            // 加载自定义控件
            LoadCustomControls();

            // 初始化表格结构
            InitTable();

            // 初始化右键菜单
            InitMenuList();

            // 初始化内存清理定时器
            InitMemoryCleanupTimer();

            // 订阅UI服务事件
            _uiService.SessionAdded += OnUISessionAdded;
            _uiService.SessionUpdated += OnUISessionUpdated;
            _uiService.MemoryStatusUpdated += OnMemoryStatusUpdated;

            // 如果需要初始化（未由启动窗体完成），则执行初始化步骤
            if (!skipInitialization)
            {
                // 加载配置
                ConfigManager.LoadConfig();

                // 附加Fiddler事件监听器
                FiddlerApp.AttachEventListeners();

                // 确保根证书已安装
                FiddlerApp.EnsureRootCertificate();

                // 启动Fiddler核心代理服务
                FiddlerApp.StartupFiddlerCore();
            }
        }

        private void LoadCustomControls()
        {
            sessionInfoPanel1 = new SessionInfoPanel(this)
            {
                Dock = DockStyle.Fill,
            };
            this.splitter1.Panel2.Controls.Add(sessionInfoPanel1);
        }





        /// <summary>
        /// 初始化数据表格的列结构和数据绑定
        /// </summary>
        private void InitTable()
        {
            // 设置表格列，显示网络会话的详细信息
            tbSessions.Columns = new AntdUI.ColumnCollection {
                new AntdUI.Column("Index", "Index") { Width = "60" },
                new AntdUI.Column("Method", "方法") { Width = "80" },
                new AntdUI.Column("Host", "主机") { Width = "150" },
                new AntdUI.Column("Url", "请求地址") { Width = "300" },
                new AntdUI.Column("StatusCode", "状态码") { Width = "80" },
                new AntdUI.Column("ContentType", "内容类型") { Width = "100" },
                new AntdUI.Column("ResponseSize", "响应大小") { Width = "100"},
                new AntdUI.Column("ResponseTime", "响应时间") { Width = "100"},
            };
            tbSessions.SetRowStyle += TbSessions_SetRowStyle;
            // 将表格绑定到会话模型列表
            tbSessions.Binding(sessionModels);

            // 添加滚动事件监听器，用于智能滚动判断
            tbSessions.ScrollBar.ValueYChanged += OnTableScrollChanged;

            InitFilter();
        }
        private Dictionary<int, string> RowStyles = new Dictionary<int, string>();
        private Table.CellStyleInfo? TbSessions_SetRowStyle(object sender, TableSetRowStyleEventArgs e)
        {
            if (RowStyles.ContainsKey(e.Index))
            {
                var rowStyle = RowStyles[e.Index];
                Color BackColor = default;
                Color ForeColor = default;

                switch (rowStyle)
                {
                    case "Red":
                        BackColor = Color.Red;
                        ForeColor = Color.White;
                        break;
                    case "Yellow":
                        BackColor = Color.Yellow;
                        ForeColor = Color.Black;
                        break;
                    case "Green":
                        BackColor = Color.Green;
                        ForeColor = Color.White;
                        break;
                }
                return new AntdUI.Table.CellStyleInfo
                {
                    BackColor = BackColor,
                    ForeColor = ForeColor
                };
            }



            return null;
        }

        /// <summary>
        /// 初始化表格的过滤器功能，为各列设置默认的过滤类型
        /// </summary>
        private void InitFilter()
        {
            foreach (var it in tbSessions.Columns)
            {
                switch (it.Key)
                {

                    case "Host":
                        it.SetDefaultFilter(typeof(string));
                        break;
                    case "Url":
                        it.SetDefaultFilter(typeof(string));
                        break;
                    case "Method":
                        it.SetDefaultFilter(typeof(string));
                        break;
                    case "StatusCode":
                        it.SetDefaultFilter(typeof(string));
                        break;
                    case "ContentType":
                        it.SetDefaultFilter(typeof(string));
                        break;
                }
            }
        }


        /// <summary>
        /// 会话模型列表，用于存储和显示捕获的网络请求
        /// </summary>
        private AntdUI.AntList<SessionModel> sessionModels = new AntdUI.AntList<SessionModel>();

        /// <summary>
        /// UI显示的最大会话数量限制
        /// </summary>
        private int MaxUiSessions => _configurationService.GetMaxUISessions();

        /// <summary>
        /// 当UI会话数量达到最大值时，清理的会话数量
        /// </summary>
        private int UiCleanupCount => _configurationService.GetUISessionCleanupCount();

        /// <summary>
        /// 标识用户是否应该自动滚动到底部（当用户在底部或接近底部时为true）
        /// </summary>
        private bool shouldAutoScroll = true;

        /// <summary>
        /// 滚动容差值，用于判断是否接近底部（像素）
        /// </summary>
        private const int ScrollTolerance = 50;

        /// <summary>
        /// UI服务会话添加事件处理方法
        /// </summary>
        /// <param name="sender">事件发送者</param>
        /// <param name="sessionModel">新添加的会话模型</param>
        private void OnUISessionAdded(object sender, SessionModel sessionModel)
        {
            if (InvokeRequired)
            {
                Invoke(new Action<object, SessionModel>(OnUISessionAdded), sender, sessionModel);
                return;
            }

            if (isCapture)
            {
                // 检查UI会话数量是否超过限制
                if (sessionModels.Count >= MaxUiSessions)
                {
                    // 清理最旧的UI会话以释放内存
                    for (int i = 0; i < UiCleanupCount && sessionModels.Count > 0; i++)
                    {
                        sessionModels.RemoveAt(0);
                    }

                    // 强制垃圾回收
                    GC.Collect();

                    System.Diagnostics.Debug.WriteLine($"已清理 {UiCleanupCount} 个旧UI会话，当前UI会话数: {sessionModels.Count}");
                }

                // 将新捕获的会话添加到模型列表中
                sessionModels.Add(sessionModel);

                // 智能滚动：只有当用户在底部或接近底部时才自动滚动
                if (shouldAutoScroll)
                {
                    tbSessions.ScrollBar.ValueY = tbSessions.ScrollBar.MaxY;
                    System.Diagnostics.Debug.WriteLine($"自动滚动到底部 - 新会话ID: {sessionModel.Id}");
                }
                else
                {
                    System.Diagnostics.Debug.WriteLine($"用户不在底部，跳过自动滚动 - 新会话ID: {sessionModel.Id}");
                }
            }
        }

        /// <summary>
        /// UI服务会话更新事件处理方法
        /// </summary>
        /// <param name="sender">事件发送者</param>
        /// <param name="sessionModel">更新的会话模型</param>
        private void OnUISessionUpdated(object sender, SessionModel sessionModel)
        {
            if (InvokeRequired)
            {
                Invoke(new Action<object, SessionModel>(OnUISessionUpdated), sender, sessionModel);
                return;
            }

            // 查找对应的会话模型并更新
            var existingSession = sessionModels.FirstOrDefault(n => n.Id == sessionModel.Id);
            if (existingSession != null)
            {
                existingSession.StatusCode = sessionModel.StatusCode;
                existingSession.ContentType = sessionModel.ContentType;
                existingSession.ResponseSize = sessionModel.ResponseSize;
                existingSession.ResponseTime = sessionModel.ResponseTime;

                System.Diagnostics.Debug.WriteLine($"会话完成更新 - ID: {sessionModel.Id}, 状态码: {sessionModel.StatusCode}");
            }
        }

        /// <summary>
        /// 内存状态更新事件处理方法
        /// </summary>
        /// <param name="sender">事件发送者</param>
        /// <param name="e">内存状态事件参数</param>
        private void OnMemoryStatusUpdated(object sender, MemoryStatusEventArgs e)
        {
            if (InvokeRequired)
            {
                Invoke(new Action<object, MemoryStatusEventArgs>(OnMemoryStatusUpdated), sender, e);
                return;
            }

            if (e.IsWarning && !string.IsNullOrEmpty(e.Message))
            {
                System.Diagnostics.Debug.WriteLine($"内存警告: {e.Message}");
                // 可以在这里添加UI提示
                // AntdUI.Message.warn(this, e.Message);
            }
        }
        /// <summary>
        /// 当Fiddler捕获到新的网络会话时触发的事件处理方法
        /// </summary>
        /// <param name="session">捕获到的网络会话对象</param>
        private void FiddlerApp_SessionAdded(Fiddler.Session session)
        {
            // 将会话添加到会话服务中，UI服务会自动处理UI更新
            _sessionService.AddSession(session);
        }

        /// <summary>
        /// 当Fiddler会话完成时触发的事件处理方法
        /// </summary>
        /// <param name="session">完成的网络会话对象</param>
        private void FiddlerApp_SessionComplete(Fiddler.Session session)
        {
            // 通知会话服务会话已完成
            _sessionService.CompleteSession(session);
        }

        public int Index = 0;
        /// <summary>
        /// 创建会话模型并填充详细信息（保留用于导入等场景）
        /// </summary>
        /// <param name="session">Fiddler会话对象</param>
        /// <returns>填充好的SessionModel对象</returns>
        private SessionModel CreateSessionModel(Session session)
        {
            var sessionModel = _uiService.ConvertToSessionModel(session);
            sessionModel.Index = ++Index;
            return sessionModel;
        }

        /// <summary>
        /// 表格滚动事件处理方法，用于智能判断是否应该自动滚动到底部
        /// </summary>
        /// <param name="sender">事件发送者</param>
        /// <param name="e">事件参数</param>
        private void OnTableScrollChanged(object sender, EventArgs e)
        {
            // 检查用户是否在底部或接近底部
            var scrollBar = tbSessions.ScrollBar;
            var distanceFromBottom = scrollBar.MaxY - scrollBar.ValueY - scrollBar.ReadSize;

            // 如果用户在底部或接近底部（在容差范围内），则启用自动滚动
            // 否则禁用自动滚动，让用户自由浏览历史数据
            shouldAutoScroll = distanceFromBottom <= ScrollTolerance;

            // 调试信息：记录滚动状态
            System.Diagnostics.Debug.WriteLine($"滚动位置: {scrollBar.ValueY}/{scrollBar.MaxY}, 距离底部: {distanceFromBottom}, 自动滚动: {shouldAutoScroll}");
        }


        /// <summary>
        /// 键盘按键事件处理方法，处理快捷键操作
        /// </summary>
        /// <param name="sender">事件发送者</param>
        /// <param name="e">键盘事件参数</param>
        private void MainForm_KeyDown(object sender, KeyEventArgs e)
        {
            // 处理Delete键删除选中会话
            if (e.KeyCode == Keys.Delete)
            {
                DeleteSelectedSessions();
                e.Handled = true;
            }
        }

        /// <summary>
        /// 删除选中的会话
        /// </summary>
        private void DeleteSelectedSessions()
        {
            var selectedIndexes = tbSessions.SelectedIndexs;
            if (selectedIndexes.Length == 0)
            {
                AntdUI.Message.warn(this, "请先选择要删除的会话");
                return;
            }

            // 确认删除操作
            var result = AntdUI.Modal.open(this, "确认删除", $"确定要删除选中的 {selectedIndexes.Length} 个会话吗？", AntdUI.TType.Warn);
            if (result != DialogResult.OK)
            {
                return;
            }

            try
            {
                // 收集要删除的会话
                List<Session> sessionsToDelete = new List<Session>();
                List<SessionModel> modelsToDelete = new List<SessionModel>();

                foreach (var index in selectedIndexes)
                {
                    if (index > 0 && index <= sessionModels.Count)
                    {
                        var sessionModel = sessionModels[index - 1];
                        if (sessionModel?.Session != null)
                        {
                            sessionsToDelete.Add(sessionModel.Session);
                            modelsToDelete.Add(sessionModel);
                        }
                    }
                }

                if (sessionsToDelete.Count > 0)
                {
                    // 从SessionService中删除会话
                    int removedCount = _sessionService.RemoveSessions(sessionsToDelete);

                    // 从UI模型列表中删除会话
                    foreach (var model in modelsToDelete)
                    {
                        sessionModels.Remove(model);
                    }

                    // 清除会话信息面板
                    sessionInfoPanel1.Clear();

                    // 执行垃圾回收
                    MemoryConfig.ForceGarbageCollection();

                    AntdUI.Message.success(this, $"成功删除 {removedCount} 个会话");
                    System.Diagnostics.Debug.WriteLine($"用户删除了 {removedCount} 个会话");
                }
            }
            catch (Exception ex)
            {
                AntdUI.Message.error(this, $"删除会话失败: {ex.Message}");
                System.Diagnostics.Debug.WriteLine($"删除会话时发生错误: {ex.Message}");
            }
        }

        /// <summary>
        /// 窗体关闭事件处理方法，确保在关闭应用时正确停止Fiddler服务
        /// </summary>
        /// <param name="sender">事件发送者</param>
        /// <param name="e">窗体关闭事件参数</param>
        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            // 停止内存清理定时器
            memoryCleanupTimer?.Stop();
            memoryCleanupTimer?.Dispose();

            // 清理所有会话数据
            FiddlerApp.Clear();

            // 停止Fiddler代理服务
            FiddlerApp.Quit();

            // 最后执行一次垃圾回收
            GC.Collect();
            GC.WaitForPendingFinalizers();
        }
        private void InitMenuList()
        {
            menuList = new AntdUI.IContextMenuStripItem[]
            {
            new AntdUI.ContextMenuStripItem("复制为cURL"),
            new AntdUI.ContextMenuStripItem("数据重发"),
            new AntdUI.ContextMenuStripItem("导出会话"),
            new AntdUI.ContextMenuStripItem("删除选中会话"),
            new AntdUI.ContextMenuStripItem("标记")
            {
                Sub=
                [
                    new ContextMenuStripItem("清除"),
                    new ContextMenuStripItem("红色"),
                    new ContextMenuStripItem("黄色"),
                    new ContextMenuStripItem("绿色")
                ]
            }
            };
        }

        /// <summary>
        /// 初始化内存清理定时器
        /// </summary>
        private void InitMemoryCleanupTimer()
        {
            if (!_configurationService.IsAutoMemoryCleanupEnabled())
                return;

            memoryCleanupTimer = new System.Windows.Forms.Timer();
            memoryCleanupTimer.Interval = _configurationService.GetMemoryCleanupInterval();
            memoryCleanupTimer.Tick += MemoryCleanupTimer_Tick;
            memoryCleanupTimer.Start();
        }

        /// <summary>
        /// 内存清理定时器事件处理方法
        /// </summary>
        /// <param name="sender">事件发送者</param>
        /// <param name="e">事件参数</param>
        private void MemoryCleanupTimer_Tick(object sender, EventArgs e)
        {
            // 执行垃圾回收
            MemoryConfig.ForceGarbageCollection();

            // 获取内存使用情况
            long memoryUsage = MemoryConfig.GetCurrentMemoryUsage();
            System.Diagnostics.Debug.WriteLine($"当前内存使用: {memoryUsage} MB");

            // 通过UI服务更新内存状态
            _uiService.UpdateMemoryStatus(memoryUsage, sessionModels.Count);
        }
        /// <summary>
        /// 表格单元格点击事件处理方法，显示选中会话的详细信息
        /// </summary>
        /// <param name="sender">事件发送者</param>
        /// <param name="e">表格点击事件参数</param>
        private void table1_CellClick(object sender, AntdUI.TableClickEventArgs e)
        {
            // 检查是否按下了Ctrl键
            bool isCtrlPressed = (Control.ModifierKeys & Keys.Control) == Keys.Control;
            // 如果没有按下Ctrl键，则清除当前会话信息并显示新选择的会话
            // 如果按下了Ctrl键，则保留当前选择，不更新会话信息面板
            if (!isCtrlPressed)
            {
                if (e.RowIndex > 0 && e.Button == MouseButtons.Left)
                {
                    // 获取点击行对应的会话模型
                    var row = e.Record as SessionModel;
                    // 获取会话详情并显示
                    if (row?.Session != null)
                    {
                        // 使用异步方法更新会话详情面板
                        Task.Run(() =>
                        {
                            // 在UI线程上清除当前会话信息
                            this.Invoke((MethodInvoker)delegate
                            {
                                sessionInfoPanel1.Clear();
                            });

                            // 短暂延迟以确保清除操作完成
                            Task.Delay(10).Wait();

                            // 在UI线程上设置新的会话
                            this.Invoke((MethodInvoker)delegate
                            {
                                sessionInfoPanel1.Session = row.Session;
                            });
                        });
                    }
                }
            }
            if (e.Button == MouseButtons.Right)
            {
                AntdUI.ContextMenuStrip.open(this, it =>
                {
                    Debug.WriteLine("点击内容：" + it.Text);

                    // 获取点击行对应的会话模型
                    var row = e.Record as SessionModel;
                    // 根据会话ID获取完整的会话对象

                    if (it.Text.Equals("复制为cURL"))
                    {
                        // 获取点击行对应的会话模型
                        if (row?.Session != null)
                        {
                            var curlStr = _sessionFormattingService.FormatRequestAsCurl(row.Session);
                            // 复制到剪贴板
                            Clipboard.SetText(curlStr);
                            AntdUI.Message.info(this, "已复制到剪切板");
                        }
                    }

                    if (it.Text.Equals("数据重发"))
                    {
                        var selectIndexs = tbSessions.SelectedIndexs;
                        foreach (var item in selectIndexs)
                        {
                            var row2 = tbSessions[item - 1].record as SessionModel;
                            if (row2?.Session != null)
                            {
                                // 数据重发
                                var newSession = _sessionService.ResendSession(row2.Session);
                                if (newSession != null)
                                {
                                    sessionModels.Add(CreateSessionModel(newSession));
                                    AntdUI.Message.info(this, "数据重发成功");
                                }
                                else
                                {
                                    AntdUI.Message.error(this, "数据重发失败");
                                }
                            }
                        }
                    }

                    if (it.Text.Equals("导出会话"))
                    {
                        List<Session> exportSessions = new List<Session>();
                        var selectIndexs = tbSessions.SelectedIndexs;

                        // 如果没有选中的行，则使用当前右键点击的行
                        if (selectIndexs.Length == 0)
                        {
                            if (row?.Session != null)
                            {
                                exportSessions.Add(row.Session);
                            }
                        }
                        else
                        {
                            // 处理多选情况
                            foreach (var item in selectIndexs)
                            {
                                var row2 = tbSessions[item - 1].record as SessionModel;
                                if (row2?.Session != null)
                                {
                                    exportSessions.Add(row2.Session);
                                }
                            }
                        }

                        if (exportSessions.Count == 0) return;

                        // 创建保存文件对话框
                        SaveFileDialog saveFileDialog = new SaveFileDialog();
                        saveFileDialog.Filter = "Fiddler会话存档文件 (*.saz)|*.saz";
                        saveFileDialog.Title = "导出会话";

                        // 根据导出会话数量设置文件名
                        string fileName = exportSessions.Count == 1
                            ? $"Session_{exportSessions[0].id}_{DateTime.Now:yyyyMMdd_HHmmss}.saz"
                            : $"Sessions_Multiple_{DateTime.Now:yyyyMMdd_HHmmss}.saz";
                        saveFileDialog.FileName = fileName;

                        if (saveFileDialog.ShowDialog() == DialogResult.OK)
                        {
                            string filename = saveFileDialog.FileName;

                            // 使用会话服务导出会话
                            bool success = _sessionService.ExportSessions(exportSessions, filename);

                            if (success)
                            {
                                AntdUI.Message.success(this, $"已成功导出 {exportSessions.Count} 个会话到: {filename}");
                            }
                            else
                            {
                                AntdUI.Message.error(this, "导出会话失败");
                            }
                        }
                    }

                    if (it.Text.Equals("删除选中会话"))
                    {
                        DeleteSelectedSessions();
                    }
                    if (it.Text.Equals("清除"))
                    {
                        if (RowStyles.ContainsKey(e.RowIndex))
                        {
                            RowStyles.Remove(e.RowIndex);
                        }
                    }
                    if (it.Text.Equals("红色"))
                    {
                        if (!RowStyles.ContainsKey(e.RowIndex))
                        {
                            RowStyles.Add(e.RowIndex, "Red");
                            tbSessions.Invalidate();
                        }
                    }
                    if (it.Text.Equals("黄色"))
                    {
                        if (!RowStyles.ContainsKey(e.RowIndex))
                        {
                            RowStyles.Add(e.RowIndex, "Yellow");
                            tbSessions.Invalidate();
                        }
                    }
                    if (it.Text.Equals("绿色"))
                    {
                        if (!RowStyles.ContainsKey(e.RowIndex))
                        {
                            RowStyles.Add(e.RowIndex, "Green");
                            tbSessions.Invalidate();
                        }
                    }


                }, menuList);
            }

        }
        AntdUI.IContextMenuStripItem[] menuList = { };
        /// <summary>
        /// 标识当前是否正在捕获网络流量的状态变量
        /// </summary>
        bool isCapture = false;

        /// <summary>
        /// 内存清理定时器，定期执行垃圾回收
        /// </summary>
        private System.Windows.Forms.Timer memoryCleanupTimer;

        /// <summary>
        /// 开始/停止抓包按钮点击事件处理方法，切换捕获状态并更新按钮显示
        /// </summary>
        /// <param name="sender">事件发送者</param>
        /// <param name="e">事件参数</param>
        private void btnStartAndStop_Click(object sender, EventArgs e)
        {
            isCapture = !isCapture;
            if (isCapture)
            {
                this.btnStartAndStop.Text = "停止抓包";
                this.btnStartAndStop.Type = AntdUI.TTypeMini.Error;
                // 订阅会话添加事件
                FiddlerApp.SessionAdded += FiddlerApp_SessionAdded;

                // 订阅会话完成事件
                FiddlerApp.SessionComplete += FiddlerApp_SessionComplete;
            }
            else
            {
                this.btnStartAndStop.Text = "开始抓包";
                this.btnStartAndStop.Type = AntdUI.TTypeMini.Primary;
                // 订阅会话添加事件
                FiddlerApp.SessionAdded -= FiddlerApp_SessionAdded;

                // 订阅会话完成事件
                FiddlerApp.SessionComplete -= FiddlerApp_SessionComplete;
            }
        }

        /// <summary>
        /// 清空按钮点击事件处理方法，清除所有捕获的会话数据
        /// </summary>
        /// <param name="sender">事件发送者</param>
        /// <param name="e">事件参数</param>
        private void btnClear_Click(object sender, EventArgs e)
        {
            _sessionService.ClearAllSessions();
            this.sessionModels.Clear();
            sessionInfoPanel1.Clear();
            FiddlerApp.Clear();
            this.Index = 0;
            // 重置自动滚动状态，清空后重新开始自动滚动
            shouldAutoScroll = true;
            // 执行垃圾回收
            MemoryConfig.ForceGarbageCollection();
            System.Diagnostics.Debug.WriteLine("会话数据已清空，重置自动滚动状态为启用");
        }

        /// <summary>
        /// 设置按钮点击事件处理方法
        /// </summary>
        /// <param name="sender">事件发送者</param>
        /// <param name="e">事件参数</param>
        private void btnSetting_Click(object sender, EventArgs e)
        {
            var setting = new Setting();
            if (AntdUI.Modal.open(this, AntdUI.Localization.Get("Setting", "设置"), setting) == DialogResult.OK)
            {

                MemoryConfig.EnableAutoMemoryCleanup = setting.EnableAutoMemoryCleanup;
                MemoryConfig.MemoryCleanupInterval = setting.MemoryCleanupInterval;
                MemoryConfig.MaxSessions = setting.MaxSessions;
                MemoryConfig.SessionCleanupCount = setting.SessionCleanupCount;
                MemoryConfig.MaxUISessions = setting.MaxUISessions;
                MemoryConfig.UISessionCleanupCount = setting.UISessionCleanupCount;
                MemoryConfig.MemoryWarningThreshold = setting.MemoryWarningThreshold;

                ConfigManager.SaveConfig();

                // 重新加载配置
                _configurationService.LoadConfiguration();

                // 重新初始化内存清理定时器
                memoryCleanupTimer?.Stop();
                memoryCleanupTimer?.Dispose();
                InitMemoryCleanupTimer();
            }
        }

        /// <summary>
        /// 导入会话按钮点击事件处理方法
        /// </summary>
        /// <param name="sender">事件发送者</param>
        /// <param name="e">事件参数</param>
        private void btnImportSessions_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "Fiddler会话存档文件 (*.saz)|*.saz";
            openFileDialog.Title = "导入会话";

            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    // 使用会话服务导入会话
                    var importedSessions = _sessionService.ImportSessions(openFileDialog.FileName);
                    if (importedSessions != null && importedSessions.Any())
                    {
                        foreach (var session in importedSessions)
                        {
                            var sessionModel = CreateSessionModel(session);
                            var exSessionModel = FiddlerApp.GetSession(sessionModel.Flagname);
                            if (exSessionModel == null)
                            {
                                sessionModels.Add(sessionModel);
                                FiddlerApp.AddSession(session);
                            }
                        }
                        AntdUI.Message.success(this, $"成功导入 {importedSessions.Count()} 个会话");
                    }
                    else
                    {
                        AntdUI.Message.warn(this, "未找到有效的会话数据");
                    }
                }
                catch (Exception ex)
                {
                    AntdUI.Message.error(this, $"导入失败: {ex.Message}");
                }
            }
        }
    }
}

